package com.frejoys.admin.controller;

import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.common.IdDto;
import com.frejoys.common.dto.common.platform.PlatformUpDto;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.common.vo.admin.PlatformVo;
import com.frejoys.service.PlatformService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Tag(name = "平台设置管理", description = "平台设置管理")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixAdmin)
@Authorization(Authority.Private)
public class AdminPlatformController {

    private final PlatformService platformService;

    private final RedissonClient redissonClient;

    @Operation(summary = "编辑平台设置")
    @PostMapping("/platform/upPlatform")
    public Result upPlatform(@RequestBody @Validated PlatformUpDto dto) {

        RLock lock = redissonClient.getLock(CacheKeyUtil.platformLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {
                platformService.upPlatform(dto);
            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }


    @Operation(summary = "查看平台设置")
    @PostMapping("/platform/platformInfo")
    public Result<PlatformVo> platformInfo(@RequestBody @Validated IdDto dto) {
        return Result.success(platformService.platformInfo(dto));
    }

}
